package com.example.c5;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import lombok.extern.slf4j.Slf4j;

/**
 * @author Jonathan
 * 2021/5/29 23:59
 */
@Slf4j
public class HelloServer {
    public static void main(String[] args) {
        log.info("hello world.");
        // 启动器 负责组装netty组件，启动服务器
        new ServerBootstrap()
                // bossEventLoop  workerEventLoop
                .group(new NioEventLoopGroup())
                .channel(NioServerSocketChannel.class)
                //  boss 负责连接  worker 负责读写
                .childHandler(
                        // 代码和客户端进行数据读写通道的初始化
                        new ChannelInitializer<NioSocketChannel>() {
                            @Override
                            protected void initChannel(NioSocketChannel nioSocketChannel) throws Exception {
                                // 将buffer转换成String
                                nioSocketChannel.pipeline().addLast(new StringDecoder());
                                nioSocketChannel.pipeline().addLast(new ChannelInboundHandlerAdapter() {
                                    @Override
                                    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
                                        log.info("msg:{}", msg);
                                    }
                                });
                            }
                        }).bind(8080);// 绑定监听端口
    }
}
